//
//  TPAlertViewController.m
//  CloudAtCostPanel
//
//  Created by leonardo on 2017/2/9.
//  Copyright © 2017年 tanpengsccd. All rights reserved.
//

#import "TPAlertViewController.h"
#import "TPUIKit.h"


#pragma mark -------------- TPAlertViewController ---------------



@class TPAlertView;
@interface TPAlertViewController ()


@property (nonatomic , strong) TPAlertView * alertView_HUD;


@end



@implementation TPAlertViewController


+ (instancetype)defaultCautionViewController{
    static TPAlertViewController * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TPAlertViewController alloc]init];
        instance.alertViewControllerType = kAlertViewControllerType_Caution;
//        instance.alertViews = [NSMutableArray new];
//        [instance addObserver:instance forKeyPath:kAlertVC options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
    });
    return  instance;
}
/**
 *  loading HUD ，只存在一个View
 *
 *  @return HUDViewController
 */
+ (instancetype)defaultHUDViewController{
    static TPAlertViewController * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TPAlertViewController alloc]init];
        instance.alertViewControllerType = kAlertViewControllerType_HUD;
//        instance.alertViews = [NSMutableArray new];
//        [instance addObserver:instance forKeyPath:kAlertVC options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];

    });
    return  instance;
}
//APN推送
//+ (instancetype)defautAPNViewController{
//    static TPAlertViewController * instance = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        instance = [[TPAlertViewController alloc]init];
//    });
//    return  instance;
//}

-(void)showAlertView:(TPAlertView *)alert animated:(BOOL)flag{
    alert.parentVC = self;
//    switch (self.alertViewControllerType) {
//        case kAlertViewControllerType_Caution:
//        {
//            
//        }
//            break;
//        case kAlertViewControllerType_HUD:
//        {
//
//            
//        }
//            break;
//            
//        default:
//            break;
//    }
    alert.showCount ++;
//    DDLogDebug(@"added:%@\nalert:%@",[self addedAlertViews],alert);

    if ([[self addedAlertViews]containsObject:alert]) {
        
    }else{
        [[UIApplication sharedApplication].keyWindow addSubview:alert];
        if ([self addedAlertViews].count == 1) {
            [self showNewView];
        }else{
            [alert setHidden:YES];
//            DDLogDebug(@"hiden:%@",alert.hidden?@"YES":@"NO");
        }
    }
    

    

    
}
#pragma mark - public
-(void)showNewView{
    [[[self addedAlertViews] firstObject] setHidden:NO];
    [[[self addedAlertViews] firstObject] didChangeValueForKey:@"hidden"];
    DDLogDebug(@"showNew:%@",[[self addedAlertViews] firstObject] );
}
#pragma mark - override
+(BOOL)automaticallyNotifiesObserversOfAlertViews{//关闭alertView 的自动通知（KVO）
    return NO;
}
#pragma mark - private

-(NSArray *)addedAlertViews{
    NSMutableArray * showedAlertViews = [UIApplication sharedApplication].keyWindow.subviews.mutableCopy;
    DDLogDebug(@"%@",showedAlertViews);
    [showedAlertViews removeObjectAtIndex:0];
    for (id object in showedAlertViews.copy) {
        if ([object isMemberOfClass:[TPAlertView class]] && (NSUInteger)[(TPAlertView *)object alertViewType] == (NSUInteger)self.alertViewControllerType) {
            
        }else{
            [showedAlertViews removeObject:object];
        }
    }
    return showedAlertViews.copy;
}

-(void)dealloc{
//    [self removeObserver:self forKeyPath:kAlertVC];
}
@end




#pragma mark ----------------------------------TPAlertView---------------------------------



typedef NS_ENUM(NSUInteger , TransmitionType) {
    TransmitionType_nil,
    TransmitionType_textField,
};

static NSString * kShowCount = @"showCount";
static NSString * khidden = @"hidden";
/**
 *  自定义alertVC：顶部（推送），中部（常用），底部
 */

@interface TPAlertView ()



    PRO_S TPView * headContainer;
        PRO_S UIImageView * titleImageView;
        PRO_S UILabel * titleLabel;
        PRO_S UILabel * subtitleLabel;
    PRO_S TPView * othersContainer;
    PRO_S TPView * btnsContainer;//常用按钮

    PRO_S NSArray<TPView *> * containers;/**< 三个容器 固定不变，只为方便循环 */
PRO_A TransmitionType transmitionType;//回传类型，textField等
@end

@implementation TPAlertView

#pragma mark ~~~life circle



/**
 *  HUD loading  单例
 *
 *  @return HUD loading单例
 */
+(instancetype)sharedHUDView_Loading{
    static TPAlertView * hudView = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hudView = [[TPAlertView alloc]initHUDView_loading];
    });
    
    return hudView;
}

-(instancetype)init{
    @throw   [NSException exceptionWithName:@"USE initPrivate" reason:nil userInfo:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
}
- (instancetype)initPrivate
{
    self = [super init];
    if (self) {
        [self addObserver:self forKeyPath:kShowCount options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
        [self addObserver:self forKeyPath:khidden options:NSKeyValueObservingOptionPrior context:nil];
//        self.hidden
    }
    return self;
}
#pragma makr - life_circle

- (void)viewDidLoad{
//    [super viewDidLoad];
    //KVO 转屏
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    //GCD 控制 视图 按队列显示
    
  
    //检测转屏
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:)name:UIDeviceOrientationDidChangeNotification object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
//    [super viewDidAppear:animated];
    
}

-(void)viewDidLayoutSubviews{
//    [super viewDidLayoutSubviews];
    
}
-(void)removeFromSuperview{
    [super removeFromSuperview];
    DDLogDebug(@"0🐱alertView dismissed:%@",self);
}
-(void)dealloc{
    [self removeObserver:self forKeyPath:kShowCount];
    [self removeObserver:self forKeyPath:khidden];
}
#pragma mark - respond

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:kShowCount]) {
        if (_showCount == 0) {
            [self removeFromSuperview];
            [self.parentVC showNewView];
        }
    }else if([keyPath isEqualToString:khidden]){
        DDLogDebug(@"change:\n%@\nhiden:%@",change,self.hidden?@"YES":@"NO");
        if (!self.hidden) {
            self.alpha = 0;
            [UIView animateWithDuration:1 animations:^{
                self.alpha = 1;
            }];
        }
    
    }
}
#pragma mark ----中部 提示弹窗 完整版-----
/**
 *  中部 提示弹窗 完整版
 */
- (instancetype)initCautionWithCenterMainViewSubViewsTitleImageType:(TitleImageType)titleImageType Title:(NSString *)title subtitle:(NSString *)subtitle btnTitles:(NSArray <NSString *> *)btnTitles{
    self = [self initPrivate];
    if (self) {
        self.alertViewType = kAlertViewType_Caution;
        //由里到外；由小到大 布局。
        //        _bgView
        //        ---------------------------------
        //        |                               |
        //        |   _headContainer              |
        //        |       _titleImageView         |
        //        |       _titleLabel             |
        //        |       _subtitleLabel          |
        //        |                               |
        //        |- - - - - - - - - - - - - - - -|  <----mainView
        //        |                               |
        //        |   _othersContainer            |
        //        |                               |
        //        |-------------------------------|
        //        |                               |
        //        |   _btnsContainer              |
        //        |                               |
        //        ---------------------------------
        //头部容器：img，title，subtitle
        [self addHeadContainerSubviewsWithTitleImageType:titleImageType title:title subtitle:subtitle];
        //其他容器：需要额外添加的 内容的容器，如输入框，选择按钮
        [self addOtherContainerSubview:nil];
        //按钮容器:水平或者垂直排列的btn
        [self addBtnsContainerSubviewsWithBtnTitles:btnTitles];
        [self addMainSubviews];
        [self addbgviewMainView];
        [self addConstraintsWithType:kAlertViewType_Caution];
        [self addAction];
        self.backgroundColor = COLOUR_TRANSLUCENT;
        self.mainView.backgroundColor = COLOUR_SOLID;
        self.mainView.layer.cornerRadius = CORNER_RADIUS;
        
        //        self.mainView.layer.borderColor = COLOUR_BLACK.CGColor;
        //        self.mainView.layer.borderWidth = 0.5;
        
        
    }
    
    return  self;
}
/**
 *  【确定】 中部
 */
- (instancetype)initOkWithTitle:(NSString *)title subtitle:(NSString *) subtitle{
    return [self initCautionWithCenterMainViewSubViewsTitleImageType:TitleImageType_warning Title:title subtitle:subtitle btnTitles:@[@"Ok"]];
}

/**
 *  【确定|取消】 中部
 */
- (instancetype)initOkCancelWithTitle:(NSString *)title subtitle:(NSString *) subtitle{
    return [self initCautionWithCenterMainViewSubViewsTitleImageType:TitleImageType_warning Title:title subtitle:subtitle btnTitles:@[@"Cancel",@"Ok"]];
}

/**
 *  textField
 */
- (instancetype)initTextFieldWithTitle:(NSString *)title subtitle:(NSString *)subtitle text:(NSString *)text placeholder:(NSString *)placeholder{
    self = [self initPrivate];
    if (self) {
        self.transmitionType = TransmitionType_textField;
        [self addHeadContainerSubviewsWithTitleImageType:TitleImageType_warning title:title subtitle:subtitle];
        [self addOthersContainer_textFieldWithText:text Placeholder:placeholder];
        [self addBtnsContainerSubviewsWithBtnTitles:@[@"Cancel",@"Ok"]];
        [self addMainSubviews];
        [self addbgviewMainView];
        [self addConstraintsWithType:kAlertViewType_Caution];
        [self addAction];
        self.backgroundColor = COLOUR_TRANSLUCENT;
        self.mainView.backgroundColor = COLOUR_SOLID;
        self.mainView.layer.cornerRadius = CORNER_RADIUS;
        
    }
    return self;
}


#pragma mark -----方状小型HUDView_loading----
/**
 *  初始化HUD类型
 */
- (instancetype)initHUDView_loading
{
    self = [self initPrivate];
    if (self) {
        self.alertViewType = kAlertViewType_HUD;
        [self addHeadContainerSubviewsWithTitleImageType:TitleImageType_none title:nil subtitle:nil];
        [self addOtherContainer_HUDView_loading];
        [self addBtnsContainerSubviewsWithBtnTitles:@[@"Cancel"]];
        [self addMainSubviews];
        [self addbgviewMainView];
        [self addConstraintsWithType:self.alertViewType];
        [self addAction];
        self.backgroundColor = COLOUR_TRANSLUCENT;
        self.mainView.backgroundColor = COLOUR_SOLID;
        self.mainView.layer.cornerRadius = CORNER_RADIUS;
    }
    return self;
}
#pragma mark ~~~private modthod

-(void)dismissAnimated:(BOOL)flag{
    switch (self.parentVC.alertViewControllerType) {
        case kAlertViewControllerType_Caution:
        {
            
        }
            break;
        case kAlertViewControllerType_HUD:
        {
            
        }
            break;
            
        default:
            break;
    }
    
    self.showCount --;

}

- (void)setAlertViewTapBtnOkBlock:(void (^)(id))alertViewTapBtnOkBlock{
    _alertViewTapBtnOkBlock = alertViewTapBtnOkBlock;
}
-(void)setAlertViewTapBtnCancelBlock:(void (^)(id))alertViewTapBtnCancelBlock{
    _alertViewTapBtnCancelBlock = alertViewTapBtnCancelBlock;
}
/**
 *  初始化 bgview 和 add mainview
 */
- (void)addbgviewMainView
{

    
    if (self.mainView.subviews.count) {


        [self addSubview:self.mainView];
        
//        self.modalPresentationStyle = UIModalPresentationCustom;//可以使 底部VC 保留不消失,只能在 初始化完成后，didload 前
    }else{
        DDLogError(@"self.mainView'subviews is nil:\n%@ ",self.mainView);
    }
}
/**
 *  初始化 mainView 和 add subview
 */
- (void)addMainSubviews
{
    
    self.mainView = [TPView new];
    self.mainView.clipsToBounds = YES;

    self.containers = @[self.headContainer , self.othersContainer , self.btnsContainer];
    for (TPView * container in self.containers) {
       
        [self.mainView addSubview:container];
        
    }
        


}
- (void)tapBtnOk:(TPButton *)btn{
//    DDLogDebug(@"%@",btn);
    id objec ;
    if (self.alertViewTapBtnOkBlock) {
        switch (_transmitionType) {
            case TransmitionType_textField:
            {
                objec = [(UITextField *)_othersContainer.subviews.firstObject text];
            }
                break;
                
            default:
                break;
        }
        self.alertViewTapBtnOkBlock(objec);
    }
    [self dismissAnimated:YES];
}

- (void)tapBtnCancel:(TPButton *)btn{
//    DDLogDebug(@"%@",btn);
    if (self.alertViewTapBtnCancelBlock) {
        self.alertViewTapBtnCancelBlock(nil);
    }
    [self dismissAnimated:YES];
}
- (void)addAction{
    if (self.btnsContainer && self.btnsContainer.subviews>0) {
        for (TPButton * btn in self.btnsContainer.subviews) {
            if ([btn.titleLabel.text isEqualToString:@"确定"]||[btn.titleLabel.text isEqualToString:@"Ok"]||[btn.titleLabel.text isEqualToString:@"Yes"]||[btn.titleLabel.text isEqualToString:@"Sure"]) {
                [btn addTarget:self action:@selector(tapBtnOk:) forControlEvents:UIControlEventTouchUpInside];
                NSLog(@"%@",btn);

                
            }else if([btn.titleLabel.text isEqualToString:@"Cancel"]){
                [btn addTarget:self action:@selector(tapBtnCancel:) forControlEvents:UIControlEventTouchUpInside];
                NSLog(@"%@",btn);
            }
        }
    }
    
}

/**
 *  收到转屏通知
 *
 *  @param noti 通知
 */
- (void)orientChange:(NSNotification *)noti
{
    [_mainView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(_mainView.superview);
    }];
    //    NSDictionary* ntfDict = [noti userInfo];
    //
    //    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
    //    /*
    //     UIDeviceOrientationUnknown,
    //     UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom
    //     UIDeviceOrientationPortraitUpsideDown,  // Device oriented vertically, home button on the top
    //     UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
    //     UIDeviceOrientationLandscapeRight,      // Device oriented horizontally, home button on the left
    //     UIDeviceOrientationFaceUp,              // Device oriented flat, face up
    //     UIDeviceOrientationFaceDown             // Device oriented flat, face down   */
    //
    //    switch (orient)
    //    {
    //        case UIDeviceOrientationPortrait:
    //
    //            break;
    //        case UIDeviceOrientationLandscapeLeft:
    //
    //
    //            break;
    //        case UIDeviceOrientationPortraitUpsideDown:
    //
    //
    //            break;
    //        case UIDeviceOrientationLandscapeRight:
    //
    //            
    //            break;
    //            
    //        default:
    //            break;
    //    }
}
#pragma mark --Center
/**
 *  添加 中部弹窗的 3个container 的 约束，不含子view
 */
- (void)addConstraintsWithType:(kAlertViewType)alertViewType{
//    [self.bgView setFrame:CGRectMake(0, 0, SCREAN_WIDTH, SCREAN_HEIGHT)];
    [self setFrame:[UIScreen mainScreen].bounds];
    
    
    for (TPView * view in self.containers) {
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.mainView);
        }];
    }
    
    [self.headContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mainView);
        
    }];
    [self.othersContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headContainer.mas_bottom);
    }];
    [self.btnsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.othersContainer.mas_bottom);
        make.bottom.mas_equalTo(self.mainView);
    }];
    
    
    [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        

        make.center.mas_equalTo(_mainView.superview);
        if(alertViewType == kAlertViewType_Caution){

            make.width.mas_equalTo(SCREAN_WIDTH_FIXED - 2* MARGIN_WINDOW);
        }else{

            make.size.mas_equalTo(CGSizeMake(LENGTH_HUD, LENGTH_HUD));
        }
        
    }];
    
}
/**
 *  初始化headContainer 和 添加 headContainer Subview
 */
- (void)addHeadContainerSubviewsWithTitleImageType:(TitleImageType)titleImageType title:(NSString *)title subtitle:(NSString *)subtitle {
    self.headContainer = [TPView new];
    
    if ((titleImageType == TitleImageType_none)&&!title&&!subtitle) {//值都为空 时，headContainer 高度为0
        [self.headContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
    }else{
        switch (titleImageType) {
            case TitleImageType_none:
                self.titleImageView = (UIImageView *)[TPView new];
                break;
            case TitleImageType_warning:
                self.titleImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"alert-waning"]];
                break;
            default:
                self.titleImageView = (UIImageView *)[TPView new];
                break;
        }
        
        //    --a--
        //    --a-b-c--
        
        self.titleLabel = [TPLabel labelWithText:title Font:FONTSIZE_TITLE];
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        self.subtitleLabel = [TPLabel labelWithText:subtitle Font:FONTSIZE_CONTENT];
        _subtitleLabel.numberOfLines = 0;
        _subtitleLabel.textAlignment = NSTextAlignmentCenter;
        _subtitleLabel.textColor = COLOUR_GRAY;
        [self.headContainer addSubviews:@[self.titleImageView , self.titleLabel , self.subtitleLabel]];
        
        [self.titleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.headContainer);
            make.width.mas_equalTo(PX(126));
            make.top.mas_equalTo(self.headContainer).offset(MARGIN_WINDOW);
            make.height.mas_equalTo((titleImageType == TitleImageType_none)?PX(0):PX(126));
        }];
        
        
        
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.titleImageView.mas_bottom).offset((titleImageType == TitleImageType_none)?0:MARGIN_CELL);
            make.left.right.mas_equalTo(self.headContainer);
            if (!title) {
                make.height.mas_equalTo(0);
            }
            
        }];
        
        [self.subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.titleLabel.mas_bottom).offset( title?MARGIN_TEXT:0);
            make.left.right.mas_equalTo(self.headContainer);
            make.bottom.mas_equalTo(self.headContainer).offset(subtitle?-MARGIN_TEXT:0);
        }];

    }
    
    
}

/**
 *  初始化BtnsContainer 和 添加 BtnsContainer Subview
 */

-(void)addBtnsContainerSubviewsWithBtnTitles:(NSArray <NSString *> *)btnTitles{
    self.btnsContainer = [TPView new];
//    self.btnsContainer.backgroundColor = COLOUR_WHITE;
    
    if (!btnTitles && !btnTitles.count ) {//为nil 或者 元素为0
        [self.btnsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];

    }else{
        TPButton * btnLast;// 上个btn
        for (NSString * btnTitle in btnTitles) {
            TPButton * btn = [[TPButton alloc]initwithNomalBtnTitleStr:btnTitle];
            btn.layer.cornerRadius = 0;
            [self.btnsContainer addSubview:btn];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(HEIGHT_BTN_SMALL);
                make.top.bottom.mas_equalTo(self.btnsContainer);
                if (btnLast) {
                    make.left.mas_equalTo(btnLast.mas_right);
                    make.width.mas_equalTo(btnLast);
                }
            }];
            btnLast = btn;
        }
        
        [self.btnsContainer.subviews.firstObject mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.btnsContainer);
        }];
        [self.btnsContainer.subviews.lastObject mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.btnsContainer);
        }];
    }
    
    
}
/**
 *  添加 OtherContainer 特殊用途
 */
- (void)addOtherContainer_HUDView_loading{
    
    
//    if (HUDType == HUDType_NONE) {
//        [self addOtherContainerSubview:nil];
//    }else{
        UIActivityIndicatorView * indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [indicator startAnimating];
        [self addOtherContainerSubview:(TPView *)indicator];
        [indicator mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.othersContainer);
            make.top.mas_equalTo(self.othersContainer).offset(MARGIN_TEXT);
            make.bottom.mas_equalTo(self.othersContainer).offset(-MARGIN_TEXT);
        }];
        
//    }
    
}
/**
 *  <#Description#>
 *
 *  @param text        <#text description#>
 *  @param placeholder <#placeholder description#>
 */
- (void)addOthersContainer_textFieldWithText:(NSString *)text Placeholder:(NSString *) placeholder{
    UITextField * textField = [[UITextField alloc]init];
    textField.textAlignment = NSTextAlignmentCenter;
    textField.layer.borderWidth = 1;
    
    textField.text = text;
    textField.placeholder =  placeholder;
    [self addOtherContainerSubview:(TPView *)textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textField.superview).offset(MARGIN_WINDOW);
        make.right.mas_equalTo(textField.superview).offset(-MARGIN_WINDOW);
        make.height.mas_equalTo(HEIGHT_CELL);
        make.top.mas_equalTo(_othersContainer).offset(MARGIN_TEXT);
        make.bottom.mas_equalTo(_othersContainer).offset(-MARGIN_TEXT);
    }];
    [textField becomeFirstResponder];
}
-(void)addOtherContainerSubview:(TPView *)view{
    self.othersContainer = [TPView new];
    if (!view) {
        [self.othersContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
    }else{
        [self.othersContainer addSubview:view];
    }
    
}


#pragma mark ---bottom---

#pragma mark ---top(APNs)---

//- (void)show{
//    
//    [[UIApplication sharedApplication].keyWindow addSubview:self.bgView];
//
//    self.mainView.transform = CGAffineTransformMakeScale(1.05, 1.05);
//    [UIView animateWithDuration:0.28 animations:^{
//        self.mainView.transform = CGAffineTransformIdentity;
//    }];
//
//    
//}







@end


